package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.util.List;
import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.databinding.ActivityCameraBinding;
import flc.ast.dialog.ProgressDialog;
import flc.ast.fragment.ToolFragment;
import stark.common.apis.ApiManager;
import stark.common.apis.base.ImgAnimalRet;
import stark.common.apis.base.ImgPlantRet;
import stark.common.apis.base.OcrBankCardRet;
import stark.common.apis.base.OcrIdCardRet;
import stark.common.base.IReqRetCallback;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    public static int type;
    private boolean isFlash = false;//判断是否打开闪光灯
    private boolean isTaken = false;//判断是否拍照
    private Bitmap mRetBitmap;
    private ProgressDialog mProgressDialog;


    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mProgressDialog = new ProgressDialog(mContext);

        mDataBinding.ivTakePhoto.setOnClickListener(this);
        mDataBinding.ivFlash.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivFlash://手电筒
                openFlash();
                break;
            case R.id.ivTakePhoto://拍照
                mDataBinding.cameraView.takePictureSnapshot();
                break;
        }
    }

    @Override
    protected void initData() {
        getPermission();
        if (type == 0) {
            mDataBinding.tvTitle.setText(getString(R.string.plant_rec));
        } else if (type == 1) {
            mDataBinding.tvTitle.setText(getString(R.string.animal_rec));
        } else if (type == 2) {
            mDataBinding.tvTitle.setText(getString(R.string.id_card_rec));
        } else if (type == 3) {
            mDataBinding.tvTitle.setText(getString(R.string.bank_card_rec));
        }
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }

            @Override
            public void onDenied(boolean needGoSettings) {
                ToastUtils.showShort(R.string.no_permission);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
//        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {

            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                int width = result.getSize().getWidth();
                int height = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (width * height > screenWidth * screenHeight) {
                    width = screenWidth;
                    height = screenHeight;
                }
                result.toBitmap(width, height, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
//                        mDataBinding.imageViewTouch.setImageBitmap(bitmap);
                        mRetBitmap = bitmap;
                        mProgressDialog.title = getString(R.string.rec_ing);
                        mProgressDialog.show();
                        mProgressDialog.sbProgress.setProgress(new Random().nextInt(60));
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mProgressDialog.dismiss();
                                if (type == 0) {
                                    plantRec();
                                } else if (type == 1) {
                                    animalRec();
                                } else if (type == 2) {
                                    idCardRec();
                                }else if (type == 3) {
                                    bankCardRec();
                                }
                            }
                        }, 1000);
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {

            }

            @Override
            public void onVideoRecordingEnd() {

            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {

            }
        });
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivFlash.setImageResource(R.drawable.ashoudiantkai);
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivFlash.setImageResource(R.drawable.aguan);
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    private void plantRec() {
        ApiManager.imgApi().identifyPlant(CameraActivity.this, mRetBitmap, new IReqRetCallback<List<ImgPlantRet>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<ImgPlantRet> result) {
                if (success) {
                    if (result != null && result.size() != 0) {
                        PlantRecActivity.sBitmap = mRetBitmap;
                        PlantRecActivity.sPlantRets = result;
                        startActivity(PlantRecActivity.class);
                    } else {
                        ToastUtils.showShort(R.string.no_find_data);
                    }
                } else {
                    ToastUtils.showShort(R.string.no_find_data);
                }
            }
        });
    }

    private void animalRec() {
        ApiManager.imgApi().identifyAnimal(CameraActivity.this, mRetBitmap, new IReqRetCallback<List<ImgAnimalRet>>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable List<ImgAnimalRet> result) {
                dismissDialog();
                if (success) {
                    if (result != null && result.size() != 0) {
                        AnimalRecActivity.sBitmap = mRetBitmap;
                        AnimalRecActivity.sAnimRets = result;
                        startActivity(AnimalRecActivity.class);
                    } else {
                        ToastUtils.showShort(R.string.no_find_data);
                    }
                } else {
                    ToastUtils.showShort(R.string.no_find_data);
                }
            }
        });
    }

    private void idCardRec() {
        ApiManager.ocrApi().identifyIdCard(CameraActivity.this, mRetBitmap, new IReqRetCallback<OcrIdCardRet>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable OcrIdCardRet result) {
                if (success) {
                    if (result != null) {
                        if (result.idcard_number_type == -1) {
                            ToastUtils.showShort(R.string.id_empty_tips);
                        } else if (result.idcard_number_type == 0) {
                            ToastUtils.showShort(R.string.id_illegal_tips);
                        } else if (result.idcard_number_type == 2) {
                            ToastUtils.showShort(R.string.gender_birth_no_equals_tips);
                        } else if (result.idcard_number_type == 3) {
                            ToastUtils.showShort(R.string.id_birth_no_equals_tips);
                        } else if (result.idcard_number_type == 4) {
                            ToastUtils.showShort(R.string.id_gender_no_equals_tips);
                        } else {
                            IdCardRecActivity.sIdCardRet = result;
                            IdCardRecActivity.sBitmap = mRetBitmap;
                            startActivity(IdCardRecActivity.class);
                        }
                    } else {
                        ToastUtils.showShort(R.string.no_find_data);
                    }
                } else {
                    ToastUtils.showShort(R.string.no_find_data);
                }
            }
        });
    }

    private void bankCardRec(){
        ApiManager.ocrApi().identifyBankCard(this, mRetBitmap, new IReqRetCallback<OcrBankCardRet>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable OcrBankCardRet result) {
                dismissDialog();
                if (success) {
                    if (result != null) {
                        BankCardActivity.sOcrBankCardRet = result;
                        BankCardActivity.sBitmap = mRetBitmap;
                        startActivity(BankCardActivity.class);
                    } else {
                        ToastUtils.showShort(R.string.no_find_data);
                    }
                } else {
                    ToastUtils.showShort(R.string.no_find_data);
                }
            }
        });
    }

}